import { Message } from '@arco-design/web-vue'
import { useI18n } from 'vue-i18n'

import { GlobalCustomCode, globalMessage } from '@/apis/message'

const isSuccess = (code: number) => code < GlobalCustomCode.BadRequest

/** code 若未定义消息则使用默认的状态码消息 */
const codeFallback = (code: number): number => {
  if (code >= GlobalCustomCode.ServerInternalError) {
    return GlobalCustomCode.UndefinedServerError
  } else if (isSuccess(code)) {
    return GlobalCustomCode.UndefinedSuccess
  }
  return GlobalCustomCode.UndefinedClientError
}

/** 使用 Message 组件展示请求返回的自定义 `code` 消息 */
export function useFetchMessage(messageMaps: Record<Locales, Record<number, string>>[]) {
  const mergedMessages = messageMaps.reduce(
    (acc, cur) => {
      const locales = Reflect.ownKeys(cur) as Locales[]
      for (const locale of locales) {
        acc[locale] = { ...acc[locale], ...cur[locale] }
      }
      return acc
    },
    { ...globalMessage }
  )

  /** @Todo 使用 i18n 的 t 函数获取消息 */
  const { locale } = useI18n<[unknown], Locales>()

  return {
    showMessage: (code: number = GlobalCustomCode.Undefined) => {
      const messageIsDefined = !!mergedMessages[locale.value][code]

      const prefix = messageIsDefined ? '' : `[${code}]: `
      const finalCode = messageIsDefined ? code : codeFallback(code)
      const content = `${prefix}${mergedMessages[locale.value][finalCode]}`

      if (isSuccess(code) && code !== GlobalCustomCode.Undefined) {
        Message.success(content)
      } else {
        Message.error(content)
      }
    }
  }
}
